<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			body{font-family: "Microsoft YaHei",serif;}
			body,dl,dd,p,h1,h2,h3,h4,h5,h6{margin:0;}
			ol,ul,li{margin:0;padding:0;list-style:none;}
			img{border:none;}
			
			#wrap{
				width: 300px;
				margin: 50px auto 0;;
				border: 2px solid #666;
				border-radius: 10px;
				user-select: none;
			}
			#wrap ul{
				padding-top: 20px;
				color: #fff;
			}
			#wrap li{
				line-height: 40px;
				text-indent: 4em;
				background: url(img/ckbg1.jpg) no-repeat 20px center/auto;
				cursor:pointer;
			}
			#wrap li.click{
				background-image: url(img/ckbg2.jpg);
			}
			div.btn{
				overflow: hidden;
				width: 100%;
				height: 20px;
				margin-top:20px;
			}
			div.btn p{
				float: left;
				font-weight: bold;
				cursor:pointer;
			}
			.all{
				width: 100px;
				margin-right: 20px;
				text-indent: 4em;
				background: url(img/ckbg1.jpg) no-repeat 20px center/auto;
			}
			.all.click{
				background-image: url(img/ckbg2.jpg);
			}
		</style>
	</head>
	<body>
		<div id="wrap">
			<ul class="list">

			</ul>
			<div class="btn">
				<p class="all">全选</p>
				<p class="reverse">反选</p>
			</div>
		</div>
	</body>
	<script type="text/javascript">
		(function(data){
			let oUl = document.querySelector(".list");
			let aLi = document.getElementsByTagName("li");
			let oAll = document.querySelector(".all");
			let oReverse = document.querySelector(".reverse");
			let len = data.length;
			let num = 0;
			
			
			//构建html内容
			(function(){
			let html="";
			let color = ["#000","#666","#999"];
			let cLen = color.length;
			for(let i=0;i<len;i++){
				html += `<li style="background-color:${color[i%cLen]}">${data[i]["txt"]}</li>`
			}
			oUl.innerHTML += html;
			})();
			
			
			//判断num的状态
			function ifAll(){
				let bool;
				bool = (num === len?"add":"remove");
				oAll.classList[`${bool}`]("click");
			};
			
			
			
			//给li添加点击事件
			(function(){
				for(let i=0;i<len;i++){
					aLi[i].onclick = function(){
						this.classList.toggle("click");
						//检测勾选的数目
						this.classList.contains("click")?num++:num--;
						ifAll();
					}
				}
			})();
			
			
			//全选与反选
			(function(){
				oAll.onclick = function(){
					this.classList.toggle("click");
					let bool = this.classList.contains("click")
					let attr = bool?"add":"remove"
						for(let i=0;i<len;i++){
							aLi[i].classList[`${attr}`]("click");
						}
						num = bool?len:0;
				}
				oReverse.onclick = function(){
						for(let i=0;i<len;i++){
							aLi[i].classList.toggle("click");
						}
						num = len-num;
						ifAll()
				}
			})();
			
			
		})(
			[
				{
					txt:"带土"
				},
				{
					txt:"斑"
				},
				{
					txt:"佩因"
				},
				{
					txt:"银时"
				},
				{
					txt:"大叔"
				}
			]
		)
	</script>
</html>
